package com.libhttp

import androidx.multidex.BuildConfig
import com.blankj.utilcode.util.LogUtils
import com.libcommon.formatDataFromJson
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject

/**
 * Created on 2022/9/9.
 * @author Joker
 * Des: 参数 拦截器
 */

class ParamInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val reqUrl = request.url.toUri().path
        var response = chain.proceed(request)

        val header = request.headers["http"]
        if (!header.isNullOrEmpty()) { //正常请求，下载文件请求过滤解密过程
            runCatching {
                //响应解密
                val oldResponseBodyStr = response.body?.string() ?: ""
                val responseData = JSONObject(oldResponseBodyStr).optString("data")
                //val newResponseBodyStr = HttpEncryptUtil.decryptParam(responseData)
                if (BuildConfig.DEBUG) {
                    LogUtils.iTag(HttpManager.TAG, "响应${request.method}=$reqUrl 参数=${formatDataFromJson(responseData)}")
                }
                response = response.newBuilder().body(responseData.toResponseBody()).build()
            }.onFailure {
                it.printStackTrace()
            }
        }
        return response
    }
}